package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    /**
     * 查询酒店elk数据
     * @param requestParams
     */
    @Override
    public PageResult getHoltelRequestParam(RequestParams requestParams) {
        try {
        //        1.获取request对象
        SearchRequest searchRequest = new SearchRequest("hotel");
//        2.创建dsl语句
//        2.1 条件语句DSL
            buildBasicQuery(requestParams, searchRequest);
//        2.2 分页
            searchRequest.source().from((requestParams.getPage()-1)*requestParams.getSize()).size(requestParams.getSize());
//        2.3 排序
            String location = requestParams.getLocation();
            if (location != null && !location.equals("")) {
                searchRequest.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
            }
//        3.发出请求
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            restHighLevelClient.close();
//        4.解析对象
            return handHotel(search);
        } catch (IOException e) {
            System.out.println("e = " + e);
        }
        return null;
    }

    @Override
    public PageResult handHotel(SearchResponse search) {
//        1.获取值
        SearchHits hits = search.getHits();
//        2.获取总条数
        long rotal = hits.getTotalHits().value;
//        3.获取查新结果对象
        SearchHit[] hits1 = hits.getHits();
        PageResult requestParams = new PageResult();
        ArrayList<HotelDoc> hotelDocs = new ArrayList<>();
//        4.解析对象
        for (SearchHit documentFields : hits1) {
//            1.得到source
            String sourceAsString = documentFields.getSourceAsString();
//            2.反序列化
            HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
//            获取排序值
            Object[] sortValues = documentFields.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            hotelDocs.add(hotelDoc);
        }
        requestParams.setTotal(rotal);
        requestParams.setHotels(hotelDocs);
        return requestParams;
    }

    /**
     * 实现搜索的自动补全功能
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
        //        1.创建request请求
        SearchRequest searchRequest = new SearchRequest("hotel");
//        2.编写dsl语句
//            2.1 query
            buildBasicQuery(params,searchRequest);
//            2.2 设置size
            searchRequest.source().size(0);
//            2.3 聚合
            buildAggregation(searchRequest);
            //        3.发出请求
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        4.解析结果
            HashMap<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = search.getAggregations();
//         4.1 根据品牌名称，获取品牌结果
            List<String> brandAgg = getAggByName(aggregations, "brandAgg");
            result.put("brand",brandAgg);
//         4.2 根据品牌名称，获取品牌结果
            List<String> cityAgg = getAggByName(aggregations, "cityAgg");
            result.put("city", cityAgg);
//         4.3 根据品牌名称，获取品牌结果
            List<String> starAgg = getAggByName(aggregations, "starAgg");
            result.put("starName", starAgg);
            return result;
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> getSuggestions(String prefix) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            // 2.准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)
            ));
            // 3.发起请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Suggest suggest = response.getSuggest();
            // 4.1.根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void buildAggregation(SearchRequest searchRequest) {
        searchRequest.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));
        searchRequest.source().aggregation(AggregationBuilders.terms("cityAgg").field("city").size(100));
        searchRequest.source().aggregation(AggregationBuilders.terms("starAgg").field("starName").size(100));
    }

    /**
     * 聚合函数查询结果
     * @param aggregations
     * @param aggName
     * @return
     */
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }
    /**
     * dsl语句封装函数
     * 查询条件抽取
     * @param requestParams
     * @param request
     */
    private void buildBasicQuery(RequestParams requestParams,SearchRequest request) {
//        1.构建BooleanQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//        2.关键子搜索
        String key = requestParams.getKey();
        if (key == null || "".equals(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }else {
            boolQueryBuilder.must(QueryBuilders.termQuery("all", key));
        }
//        2.城市条件
        String city = requestParams.getCity();
        if (city != null && !city.equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));
        }
//        3.品牌条件
        String brand = requestParams.getBrand();
        if (brand != null && !brand.equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }
//        4.星级条件
        String starName = requestParams.getStarName();
        if (starName != null && !starName.equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }
//        5.价格
        Integer maxPrice = requestParams.getMaxPrice();
        Integer minP1rice = requestParams.getMinPrice();
        if (maxPrice != null && minP1rice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(maxPrice).gte(minP1rice));
        }
//        6.算法控制
        FunctionScoreQueryBuilder isAD = QueryBuilders.functionScoreQuery(
//                原始查询，相关性算分
                boolQueryBuilder,
//                function score的数据
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
//                        其中的一个function score元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
//                                过滤条件
                                QueryBuilders.termQuery("isAD", true),
//                              算法函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );
//
//        发出请求
        request.source().query(isAD);
    }
}
